const http = require('http');
const net = require('net');
const PORT = 5088;
const { fileDisplay, createCrud, getDatabase } = require('./server.js');
// 检测端口是否被占用
function testPort() {
	return new Promise((resolve) => {
		const server = net
			.createServer()
			.once('error', (err) => {
				if (err.code === 'EADDRINUSE' || err.code === 'EACCES') {
					resolve(false);
				} else {
					resolve(false);
				}
			})
			.once('listening', () => {
				server
					.once('close', () => {
						resolve(true);
					})
					.close();
			})
			.listen(PORT);
	});
}
// 启动服务
testPort().then((res) => {
	if (res) {
		http
			.createServer(function (request, response) {
				// 发送 HTTP 头部
				response.writeHead(200, {
					'Content-Type': 'application/json;charset=utf-8',
					'Access-Control-Allow-Origin': '*',
					'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, DELETE',
					'Access-Control-Allow-Headers': 'content-type,x-requested-with,x-ui-request,lang',
				});
				// 接收参数
				let postData = '';
				request.on('data', (chunk) => {
					postData += chunk;
				});
				//end
				request.on('end', () => {
					// 这里的postData就是前端传过来的参数
					switch (request.url) {
						//创建
						case '/create':
							createCrud(postData).then((res) => {
								response.end(JSON.stringify(res));
							});
							break;
						case '/database':
							getDatabase(postData).then((res) => {
								response.end(JSON.stringify(res));
							});
							break;
						default:
							// 返回云函数列表
							fileDisplay().then((res) => {
								response.end(JSON.stringify(res));
							});
							break;
					}
					// response.end(JSON.stringify(params));
				});
			})
			.listen(PORT);
		console.log('crud server running at http://localhost:' + PORT);
	}
});
